package com.yssoft.controller.core;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yssoft.entity.core.*;
import com.yssoft.service.core.AccountsService;
import com.yssoft.service.core.CodeService;
import com.yssoft.service.core.DdDetailService;
import com.yssoft.service.core.DepartmentService;
import com.yssoft.service.core.PersonService;
import com.yssoft.utils.UploadFile;
import com.yssoft.utils.UserHelper;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.text.ParseException;
import java.util.*;

/**
 * @author 陈翼东
 * @time 2018/4/24 下午 02:20
 * @说明 人员管理控制器
 */
@Controller
@RequestMapping("/person")
public class PersonController {
    
    
    @Resource
    private PersonService personService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private CodeService codeService;
    @Resource
    private DdDetailService ddDetailService;
    @Resource
    private AccountsService accountService;
    
    /**
     * 跳转到人员信息页面
     * @return
     */
    @RequestMapping("/personPage")
    public String findPersonPage() {
        return "core/person/personList";
    }
    
    /**
     * 获取人员信息数据
     *
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping("/findPersonPage")
    @ResponseBody
    public JSONObject findPersonPage(@RequestParam(name = "page", defaultValue = "0") int page, @RequestParam(name = "limit", defaultValue = "10") int limit, String personName, String deptName, String companyName) {
        JSONObject jsonObject = personService.queryPersonPage(page, limit, personName, deptName, companyName);
        return jsonObject;
    }
    
    /**
     * 跳转到添加人员信息页面
     *
     * @return
     */
    @RequestMapping("personEditPage")
    public String personEditPage(String personId, Model model, String detail) {
        if (personId != null && personId.trim().length() > 0) {
            //修改
            TPersonnel person = personService.queryPersonById(personId);
            if (person!=null && person.gettDId() != null) {
                TDepartment department = departmentService.queryTDepartmentById(person.gettDId());
                model.addAttribute("department", department);
            }
            List<TPersonnelAtt> personImgIdCardList = personService.queryPersonIdCardImg(person);
            List<TPersonnelAtt> personImgQualificationList = personService.queryPersonQualificationImg(person);
            List<TPersonnelAtt> personImgHealthList = personService.queryPersonHealthImg(person);
            model.addAttribute("personImgIdCardList", personImgIdCardList);
            model.addAttribute("personImgQualificationList", personImgQualificationList);
            model.addAttribute("personImgHealthList", personImgHealthList);
            model.addAttribute("person", person);
            model.addAttribute("detail", detail);
        }
        //查询字典
        Map<String ,Object> titleParam=new HashMap<>();
        titleParam.put("classify","titles");
        List<TCode> titles = codeService.findCodeByParam(titleParam);//职称
        Map<String ,Object> titleParam2=new HashMap<>();
        titleParam2.put("classify","major");
        List<TCode> major = codeService.findCodeByParam(titleParam2);//专业
        Map<String ,Object> titleParam3=new HashMap<>();
        titleParam3.put("classify","education");
        List<TCode> education = codeService.findCodeByParam(titleParam3);//文化程度
         Map<String ,Object> titleParam4=new HashMap<>();
        titleParam4.put("classify","duties");
        titleParam4.put("companyId",UserHelper.getCurrentCompanyId());
        List<TDdDetail> job = ddDetailService.findDdDetailByParam(titleParam4);//职务
        model.addAttribute("titles", titles);
        model.addAttribute("major", major);
        model.addAttribute("education", education);
        model.addAttribute("job", job);
        return "core/person/personEdit";
    }
    
    /**
     * 保存人员信息
     *
     * @param
     * @return
     */
    @RequestMapping("savePerson")
    public String savePerson(TPersonnel personnel, HttpServletRequest request,String[] idCardFileId,String[] healthCertificateFileId, String[] qualificationCertificateFileId) {
        if (personnel.getId() != null) {
            //修改
            TPersonnel oldPerson = personService.queryPersonById(personnel.getId().toString());
            personnel.setCreateTime(oldPerson.getCreateTime());
            personService.editPerson(personnel,request,idCardFileId,healthCertificateFileId,qualificationCertificateFileId);
        } else {
            //添加
            personService.addPerson(personnel,request,idCardFileId,healthCertificateFileId,qualificationCertificateFileId);
        }
        return "redirect:personPage";
    }
    
    /**
     * 上传人员图片信息
     * @param file
     * @param type
     * @return
     */
    @RequestMapping("uploadImgs")
    @ResponseBody
    public Object savePerson(@RequestParam(name = "file",required = false) MultipartFile file,String type){
        if(file.getOriginalFilename().length()>0) {
            TPersonnelAtt personnelAtt = personService.uploadImg(file, type);
            Object result=JSONObject.parse("{'id':'"+personnelAtt.getId()+"',url:'"+personnelAtt.getUrl()+"',turl:'"+personnelAtt.getTurl()+"'}");
            return result;
        }else{
            return "";
        }
    }
    
    
    /**
     * 删除人员信息
     *
     * @param personId
     * @return
     */
    @RequestMapping("/delPerson")
    @ResponseBody
    public String delPerson(String personId) {
        int result = personService.deletePersonById(personId);
        if (result > 0) {
            return "success";
        } else {
            return "error";
        }
    }
    
    /**
     * 多选删除人员信息
     *
     * @param personIds
     * @return
     */
    @RequestMapping("/delPersons")
    @ResponseBody
    public String delPersons(String personIds) {
        String[] personIdArray = personIds.split(",");
        try {
            for (String s : personIdArray) {
                personService.deletePersonById(s);
            }
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
        
    }
    
    
    /**
     * 查询企业中部门信息Tree页面
     *
     * @return
     */
    @RequestMapping("/queryMyDeptPage")
    public String queryMyDeptPage(Model model) {
        List<Map<String, Object>> jsonArray = departmentService.queryMyDeptTree();
        model.addAttribute("json", JSONArray.toJSON(jsonArray));
        return "core/person/deptTree";
    }
    
    /**
     * 修改基本资料
     *
     * @return
     */
    @RequestMapping("personEdit")
    public String personEdit( Model model, String detail,HttpServletRequest request) {
    	Integer personId = accountService.queryAccById(UserHelper.getCurrentUserId()).gettPId();
        
            //修改
            TPersonnel person = personService.queryPersonById(personId.toString());
            if (person!=null && person.gettDId() != null) {
                TDepartment department = departmentService.queryTDepartmentById(person.gettDId());
                model.addAttribute("department", department);
            }
            model.addAttribute("person", person);
            model.addAttribute("detail", true);
       
        //查询字典
        Map<String ,Object> titleParam=new HashMap<>();
        titleParam.put("classify","titles");
        List<TCode> titles = codeService.findCodeByParam(titleParam);//职称
        Map<String ,Object> titleParam2=new HashMap<>();
        titleParam2.put("classify","major");
        List<TCode> major = codeService.findCodeByParam(titleParam2);//专业
        Map<String ,Object> titleParam3=new HashMap<>();
        titleParam3.put("classify","education");
        List<TCode> education = codeService.findCodeByParam(titleParam3);//文化程度
         Map<String ,Object> titleParam4=new HashMap<>();
        titleParam4.put("classify","duties");
        titleParam4.put("companyId",UserHelper.getCurrentCompanyId());
        List<TDdDetail> job = ddDetailService.findDdDetailByParam(titleParam4);//职务
        model.addAttribute("titles", titles);
        model.addAttribute("major", major);
        model.addAttribute("education", education);
        model.addAttribute("job", job);
        return "core/person/personEdit1";
    }
    
    /**
     * 保存人员信息-修改基本信息用
     *
     * @param
     * @return
     */
    @RequestMapping("savePerson1")
    public String savePerson1(TPersonnel personnel,HttpServletRequest request,String[] idCardFileId,String[] healthCertificateFileId, String[] qualificationCertificateFileId) {
            TPersonnel oldPerson = personService.queryPersonById(personnel.getId().toString());
            personnel.setCreateTime(oldPerson.getCreateTime());
            personService.editPerson(personnel,request, idCardFileId, healthCertificateFileId, qualificationCertificateFileId);
        return "redirect:personEdit";
    }
    /**
     * 修改密码
     *
     * @param
     * @return
     */
    @RequestMapping("passwordEdit")
    public String passwordEdit() {
        return "core/person/passwordEdit";
    }
    /**
     * 修改密码-保存
     *
     */
    @RequestMapping("savePassword")
    @ResponseBody
    public String savePassword(String oldPassword,String newPassword) {
    	TAccounts acc = accountService.queryAccById(UserHelper.getCurrentUserId());
    	String msg="";
    	String newSashPassword = new SimpleHash("MD5", oldPassword == null ? "" : oldPassword, acc.getSalt(), 2).toString();
    	if(newSashPassword.contains(acc.getPassword())){
    		 String salt= System.currentTimeMillis()+acc.gettPId()+"";
             acc.setSalt(salt);//随机加密盐
             String password = new SimpleHash("MD5", newPassword, salt, 2).toString();
             acc.setPassword(password);
             accountService.updateAccountById(acc);
             msg="0";
    	}else{
    		msg="1";
    	}
        return msg;
    }
   
    @RequestMapping("deleteImg")
    @ResponseBody
   public String deleteImg(String imgId){
        try {
            personService.deleteImg(imgId);
            return "1";
        } catch (Exception e) {
            return "0";
        }
    }
    
    /**
     * @方法名称: checkPhone
     * @功能描述: 校验联系电话是否重复
     * @作者: 洪丰
     * @创建时间:2018年6月26日 下午2:12:05
     * @param checkCode
     * @return String
     */
	@RequestMapping(value = "checkPhone", method = RequestMethod.POST)
	@ResponseBody
	public String checkPhone(@RequestParam(value = "checkPhone") String checkPhone) {
		String result = "1";
		TPersonnel person = new TPersonnel();
		person.setPhone(checkPhone);
		person.setDeleteFlag("0");
		int resultInt = personService.queryPersonByRecord(person);
		if(resultInt > 0){
			result = "0";
		}
        return result;
	}
	/**
	 * @方法名称: checkIdcard
	 * @功能描述: 校验身份证是否重复
	 * @作者: 王永宁
	 * @创建时间:2018年7月13日 上午11:59:05
	 * @param checkIdcard
	 * @return String
	 */
	@RequestMapping(value = "checkIdcard", method = RequestMethod.POST)
	@ResponseBody
	public String checkIdcard(@RequestParam(value = "checkIdcard") String checkIdcard) {
		String result = "1";
		TPersonnel person = new TPersonnel();
		person.setIdcard(checkIdcard);
		person.setDeleteFlag("0");
		int resultInt = personService.queryPersonByRecord(person);
		if(resultInt > 0){
			result = "0";
		}
		return result;
	}
    
}
